import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import FdCollectionBaseComponent from '../../common/collection-base/fd-collection-base';
import { TableTdProp } from '../property/td-property-config';
import { DgControl, DomService } from '@farris/designer-services';
import { BuilderHTMLElement } from '@farris/designer-element';
import FdInputGroupComponent from '../../../input/input-group/component/fd-input-group';

/**
 * 单元格组件
 */
export default class FdTableTdComponent extends FdCollectionBaseComponent {

    triggerBelongedComponentToMoveWhenMoved = false;

    constructor(component: any, options: any) {
        super(component, options);
        this.viewModelId = this.parent.viewModelId;
        this.componentId = this.parent.componentId;



        this.components = [];
    }


    attach(element: HTMLElement): Promise<any> {
        const superAttach: any = super.attach(element);

        // 为了拖拽过程中获取标签单元格的实例，在可拖拽元素上注册组件实例
        if (this.parent.component.devMode === 'simple') {
            const tdLabelElement = element.getElementsByClassName('tdLabel');
            if (tdLabelElement && tdLabelElement[0]) {
                (tdLabelElement[0] as BuilderHTMLElement).componentInstance = this;
            }
        }

        this.setTdEditorBasicInfoMap();

        return superAttach;
    }

    /**
     * 判断是否可以接收拖拽新增的子级控件
     */
    canAccepts(el: BuilderHTMLElement) {
        return false;
    }


    /**
     * 获取单元格可以拖拽的最外层容器：即为当前所属表格table
     */
    getDragScopeElement(): HTMLElement {
        return this.parent.element;
    }

    /**
     * 点击事件
     * @param e d
     */
    onComponentClicked(e?: PointerEvent) {
        if (e) {
            e.preventDefault();
            e.stopPropagation();
        }

        return;
    }
    /**
     * 外部触发的单元格点击事件
     */
    triggerComponentClick(): void {
        super.triggerComponentClick();
        const tdEle = this.options.parent.getTdElement(this.component.id);
        this.options.parent.triggerTdClick(tdEle);

    }

    /**
     * 点击单元格触发的事件：用于高级表格
     * @param tdEle 单元格DOM元素
     * @param e 事件
     */
    triggerComponentClicked(tdEle?: HTMLElement, e?: MouseEvent) {
        this.parent.clearSelected();
        if (tdEle) {
            tdEle.classList.add('dgComponentSelected');

            if (!tdEle.getAttribute('style').includes('border-width')) {
                const borderWidth = (this.parent.component.border && this.parent.component.border.width ? this.parent.component.border.width : 1) + 1;

                let tdStyle = tdEle.getAttribute('style');
                tdStyle += ';border-width:' + borderWidth + 'px !important;';
                tdEle.setAttribute('style', tdStyle);
            }
        }

        // 切换到单元格的属性面板
        this.parent.emit('componentClicked', { componentInstance: this, needUpdatePropertyPanel: true, e });
    }

    /**
     * 取消选中后，需要移除单元格上附加的边框宽度样式
     */
    afterComponentCancelClicked() {
        const tdStyle = this.element.getAttribute('style');
        const styleWithoutBorderWidth = tdStyle.split(';').filter(style => style && !style.startsWith('border-'));
        this.element.setAttribute('style', styleWithoutBorderWidth.join(';'));

        this.parent.tdManager.targetTdId = null;
        this.parent.tdManager.targetMergedTdIds = [];
    }

    afterComponentClicked(e?: PointerEvent): void {

    }

    /**
     * 组装属性面板配置数据
     */
    getPropertyConfig(): ElementPropertyConfig[] {
        const serviceHost = this.options.designerHost;
        const prop: TableTdProp = new TableTdProp(serviceHost, this.viewModelId, this.componentId);
        const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component, this.parent.component.devMode === 'simple');

        return propertyConfig;
    }
    onPropertyChanged(changeObject: FormPropertyChangeObject): void {

        // 简单列表修改编辑器单元格的必填、标签、以及更换绑定字段、控件类型后，要同步到标签单元格
        if (this.parent.component.devMode === 'simple' && this.component.groupId) {
            if (['require', 'title', 'binding', 'type', 'placeHolder'].includes(changeObject.propertyID)) {
                this.setLabelTdProperty();
            }
        }
        this.parent.onPropertyChanged(changeObject);
    }

    /**
     * 设置标签单元格的属性
     */
    setLabelTdProperty() {
        const { labelTdElement } = this.parent.getTdElementsInSameGroup(this.component.groupId);
        const labelTdId = labelTdElement && labelTdElement.getAttribute('id');

        if (labelTdId && this.parent.component && this.parent.component.rows) {
            for (const row of this.parent.component.rows) {
                if (row.columns && row.columns.length) {

                    const tdComponent = row.columns.find(co => co.tdType === 'staticText' && co.id === labelTdId);
                    if (tdComponent) {
                        tdComponent.staticText.text = this.component.editor.title || '';
                        tdComponent.staticText.require = this.component.editor.require;
                        return;
                    }

                }

            }
        }

    }
    /**
     * 设置单元格内编辑器的映射信息，用于交互面板已绑定事件窗口
     */
    private setTdEditorBasicInfoMap() {
        if (this.component.tdType !== 'editor' || !this.component.editor || !this.component.editor.binding) {
            return;
        }
        const editor = this.component.editor;
        const domService = this.options.designerHost.getService('DomService') as DomService;

        // 列的展示名称和路径
        domService.controlBasicInfoMap.set(editor.id, {
            showName: editor.title || '',
            parentPathName: `表格 > 单元格 > ${editor.title}`
        });

        // 智能输入框内部嵌套的弹窗按钮路径信息
        if (editor.type === DgControl.InputGroup.type) {
            const inputGroupControl = new FdInputGroupComponent(editor, this.parent.options);
            inputGroupControl.setComponentExtendInfoMap();
        }
    }
}
